/*  header-comment
/*  file   : /Users/allan/Desktop/workSpace/react-hrm-h5/src/modules/preview/index
/*  author : arida
/*  date   : 2017-6-4 18:25:27
/*  last   : 2017-10-2 15:48:51
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import autobind from "autobind-decorator";

import { Button } from "@ali/ding-ui";
import classnames from "classnames";
import "./index.less";

// components
import Card from "./card";
import Avatar from "../growth/avatar";

import ProduceComponent from "../../components/produceComponent";
import getComponents from "./getComponents";

// utils
import navigate from "../../utils/navigation.js";
import {
  goBack,
  setRight,
  setTitle,
  confirm,
  alert,
  toast,
  actionSheet
} from "../../utils/dingtalk";
import { type } from "../../utils/common.js";
import { get, set } from "../../utils/db.js";

// actions
import {
  fetchAllFields,
  fetchUser,
  inviteEmp,
  deleteEmp,
  getProfile
} from "../../actions/preview/index.js";

import {
  showOrHideFooterBar,
} from "../../actions/footbar/index.js";


// 其他信息
let customList = [];
// 录用审批信息
let entryApprovalItems = [];

function goTo(hash) {
  window.location.hash = hash;
  // openLink(`#/${hash}`);
}

// 避免icon 闪动
function showCertIcon(certed) {
  return type(certed) === "boolean" ? true : false;
}

function getFromMessage({ opSourceType, opUserName }) {
  if (!opSourceType && !opUserName) return "";
  if (!opSourceType) return `来源：通过${opUserName}添加`;
  if (!opUserName) return `来源：通过${opSourceType}添加`;
  if (opSourceType === "二维码") return `来源：通过${opUserName}分享的${opSourceType}办理入职`;
  return `来源：通过${opUserName}的${opSourceType}添加`;
}

//将store注入组件的props
const mapStateToProps = state => ({
  welcome: { ...state.WELCOME_USER },
  growth: state.GROWTH_USERINFO
});
//将action与dispatch进行绑定并注入组件的props
const mapDispatchToProps = dispatch => ({
  //区分绑定到props的action与传递的props
  actions: bindActionCreators(
    {
      dispatch,
      fetchUser,
      fetchAllFields,
      getProfile,
      showOrHideFooterBar
    },
    dispatch
  )
});

@connect(mapStateToProps, mapDispatchToProps)
export default class Preview extends Component {
  static defaultProps = {
    welcome: {
      user: {}
    }
  };
  //propTypes 验证
  static propTypes = {
    welcome: PropTypes.object.isRequired,
    actions: PropTypes.shape({
      dispatch: PropTypes.func.isRequired,
      fetchUser: PropTypes.func.isRequired,
      fetchAllFields: PropTypes.func.isRequired,
      getProfile: PropTypes.func.isRequired,
      showOrHideFooterBar: PropTypes.func.isRequired
    }).isRequired
  };
  constructor(props) {
    super(props);
    this.state = {
      processInstanceId: "",
      isOnjob: false
    };
  }

  componentDidMount(){
    const { showOrHideFooterBar } = this.props.actions;
    showOrHideFooterBar && showOrHideFooterBar(false);
  }

  getFetchData(){
    
    this.props.actions.getProfile({ userId: get("userId") });
    this.props.actions.fetchAllFields(get("userId")).then(res => {
      if (res.success && res.result.items) {
        customList = res.result.items;
        entryApprovalItems = res.result.entryApprovalItems || [];

        // re-render
        const {
          name,
          avatar,
          uid,
          corpId,
          processInstanceId,
          employeeStatus,
          opUserName,
          certUploaded,
          opSourceType,
          submitEntryTable,
          modifiedEntryTableTime,
          idVerified
        } = res.result;
        if (employeeStatus === "4") {
          // 已离职，title改为个人档案
          setTitle({
            title: "个人档案"
          });
        }
        this.setState({
          profile: {
            name,
            avatar,
            uid,
            corpId,
            employeeStatus,
            opUserName, // 被谁添加
            opSourceType, // 通过什么方式添加
            submitEntryTable,
            modifiedEntryTableTime,
            certUploaded,
            idVerified
          },
          processInstanceId
        });
      }
    });

    // 查询员工在职还是待入职
    this.props.actions.fetchUser().then(res => {
      if (res.result === -1) {
        // 在职
        this.setState({ isOnjob: true });
        setTitle({
          title: "个人档案"
        });
      } else {
        this.setState({ isOnjob: false });
        setTitle({
          title: "入职登记表"
        });
      }
    });
  }
  componentWillMount() {
    setRight({
      show: false
    });
    this.getFetchData();
  }

  // componentDidMount() {
  //   const mask = alimask('dingding',{
  //     font: '20px'
  //   });
  //   console.log(document.querySelectorAll('.preview-card'));
  //   document.querySelectorAll('.preview-card').forEach((el)=>{
  //     // el.style.backgroundImage = mask;
  //     el.style.backgroundColor = 'red';
  //     console.log('set');
  //   })
  // }

  handleDeleteEmp() {
    const { profile = {} } = this.state;
    confirm({
      message: `是否将${profile.name}从待入职中删除`,
      buttonLabels: ["确认", "取消"],
      cb: res => {
        if (res.buttonIndex === 0) {
          deleteEmp(get("userId")).then(res => {
            if (res.success) {
              set("refreshPreList", true);
              goBack({});
            }
          });
        }
      }
    });
  }
  componentWillUnmount() {
    const { showOrHideFooterBar } = this.props.actions;
    window.needReload = null;
    showOrHideFooterBar && showOrHideFooterBar(true);

  }
  //重新加载
  @autobind
  needReload() {
    const t = this;
    window.needReload = () => {
      if (window.location.href.toLocaleLowerCase().indexOf("preview") !== -1) {
        // 简单粗暴
        // window.location.reload();
        // 没时间抽离逻辑，需求太赶了。
        t.getFetchData();
      }
    };
  }
  @autobind
  showActionSheet(isEdit) {
    const  hasPermission = (window.__auth && window.__auth.hasPermission) || false;
    const { processInstanceId, isOnjob } = this.state;
    const title = isOnjob ? "邀请完善个人信息" : "邀请完善入职登记表";
    const userInfo = this.props.growth.user || {};
    const baseInfo = userInfo.baseInfo || {};
    const isSelf = this.props.location.query.isSelf === "true";
    const actionSheetTitle = "请选择编辑员工档案方式";
    // 自己只能编辑信息
    if (isSelf && hasPermission) {
      const BUTTONS = ["编辑员工个人档案"];
      return actionSheet({
        title: actionSheetTitle,
        cancelButton: "取消", //取消按钮文本
        otherButtons: BUTTONS,
        onSuccess: ({ buttonIndex }) => {
          if (buttonIndex === 0) {
            // 2017-11-15： 新增功能，HR可以编辑员工信息
            //openLink(`?userId=${baseInfo.userId}#steps`);
            // if(isSelf){
            //   window.location.hash = `hrcenter/steps?userId=${baseInfo.userId}`;
            // }else{
            //   window.location.hash = `steps?userId=${baseInfo.userId}`;
            // }
            window.location.hash = `steps?userId=${baseInfo.userId}`;
            this.needReload();
          }
        }
      });
    }
    if (processInstanceId) {
      const BUTTONS = isEdit
        ? ["编辑员工个人档案", title]
        : ["确认入职", title, "查看录用审批", "删除"];
        actionSheet({
        title: actionSheetTitle,
        cancelButton: "取消", //取消按钮文本
        otherButtons: BUTTONS,
        onSuccess: ({ buttonIndex }) => {
          if (isEdit) {
            if (buttonIndex === 0) {
              // 2017-11-15： 新增功能，HR可以编辑员工信息
              //openLink(`?userId=${baseInfo.userId}#steps`);

              // if(isSelf){
              //   window.location.hash = `hrcenter/steps?userId=${baseInfo.userId}`;
              // }else{
              //   window.location.hash = `steps?userId=${baseInfo.userId}`;
              // }  
              window.location.hash = `steps?userId=${baseInfo.userId}`;
              this.needReload();
            } else if (buttonIndex === 1) {
              this.handleInvite();
            }
          } else {
            if (buttonIndex === 0) {
              window._rlog(`_profile_set_confirmEntry`);
              this.confirmEntry();
            }
            if (buttonIndex === 1) {
              window._rlog(`_profile_set_handleInvite`);
              this.handleInvite();
            }
            if (buttonIndex === 2) {
              window._rlog(`_profile_set_aflow`);
              navigate({
                system: "aflow",
                corpId: get("corpId"),
                id: processInstanceId
              });
            }
            if (buttonIndex === 3) {
              window._rlog(`_profile_set_delete`);
              this.handleDeleteEmp();
            }
          }
        }
      });
    } else {
      const BUTTONS = isEdit ? ["编辑员工个人档案", title] : ["确认到岗", title, "删除"];
      actionSheet({
        title: actionSheetTitle,
        cancelButton: "取消", //取消按钮文本
        otherButtons: BUTTONS,
        onSuccess: ({ buttonIndex }) => {
          if (isEdit) {
            if (buttonIndex === 0) {
              // 2017-11-15： 新增功能，HR可以编辑员工信息
              //openLink(`?userId=${baseInfo.userId}#steps`);
              // if (isSelf) {
              //   window.location.hash = `hrcenter/steps?userId=${baseInfo.userId}`;
              // } else {
              //   window.location.hash = `steps?userId=${baseInfo.userId}`;
              // }
              window.location.hash = `steps?userId=${baseInfo.userId}`;
              
              this.needReload();
            } else if (buttonIndex === 1) {
              window._rlog(`_profile_set_handleInvite`);
              this.handleInvite();
            }
          } else {
            if (buttonIndex === 0) {
              window._rlog(`_profile_set_confirmEntry`);
              this.confirmEntry();
            }
            if (buttonIndex === 1) {
              window._rlog(`_profile_set_handleInvite`);
              this.handleInvite();
            }
            if (buttonIndex === 2) {
              window._rlog(`_profile_set_delete`);
              this.handleDeleteEmp();
            }
          }
        }
      });
    }
  }

  handleInvite() {
    confirm({
      message: "是否邀请员工继续完善信息, 员工会收到钉钉小秘书的消息推送",
      buttonLabels: ["取消", "确认"],
      cb: res => {
        if (res.buttonIndex === 1) {
          inviteEmp(get("userId")).then(res => {
            if (res.success) {
              toast({
                text: "已发送"
              });
            }
          });
        }
      }
    });
  }

  @autobind
  confirmEntry() {
    // 重新调用接口， 免得在这个期间HR点击了确认到岗
    this.props.actions.fetchUser().then(res => {
      if (res.result === -1) {
        alert({ message: "该员工已被确认入职" });
      } else {
        goTo("confirm");
      }
    });
  }

  render() {
    const { profile = {}, isOnjob } = this.state;
    const userInfo = this.props.growth.user || {};
    const baseInfo = userInfo.baseInfo || {};
    const { position, onJobCompanyName, confrimJoinTime } = baseInfo;
    const perfectFlag = userInfo.perfectFlag;

    const  hasPermission = (window.__auth && window.__auth.hasPermission) || false;

    if (!userInfo) {
      return null;
    }

    let workDaysContent = "";
    if (confrimJoinTime) {
      workDaysContent = userInfo.workDaysContent;
    }

    // 如果是自己的话， 不能进行操作（确认到岗，删除等）
    const isSelf = this.props.location.query.isSelf === "true";

    const { isEdit = true } = this.props.welcome.user || {};
    // console.info("uid", profile.uid, "corpId", profile.corpId);

    let sucessIcon =
      profile.idVerified === true
        ? "https://gw.alicdn.com/tfs/TB1mkxJa5qAXuNjy1XdXXaYcVXa-363-363.png"
        : "";
    if (profile.idVerified === false) {
      sucessIcon =
        "https://gw.alicdn.com/tfs/TB1mQxJa5qAXuNjy1XdXXaYcVXa-363-363.png";
    }
    console.info("user: ", profile);

    return (
      <div className={`preview-layout ${isOnjob ? "preview-onJob" : ""}`}>
        <div className={`scroll-body ${isSelf && !hasPermission ? 'no-padding-bottom' : ''}`}>
          <div className="cert-show">
            <img src={sucessIcon} className="cert-icon" />
          </div>

          {/* <ProfileLink
              username={profile.name}
              avatar={profile.avatar}
              userId={get("userId")}
              corpId={profile.corpId}
          /> */}
          <Avatar
            userInfo={{
              ...baseInfo,
              position,
              perfectFlag,
              onJobCompanyName,
              workDaysContent,
              name: profile.name,
              from: getFromMessage({
                opSourceType: profile.opSourceType,
                opUserName: profile.opUserName
              })
            }}
          />
          {entryApprovalItems
            .map(item => ({
              list: getComponents(item.customFieldVOList || []),
              title: item.title
            }))
            .map(({ list, title }, idx) => (
              <Card key={idx} title={title} className="entry-approval">
                <ProduceComponent list={list || []} />
              </Card>
            ))}
          {!isEdit && (
            <div className="preview-form-title preview-card-title">
              <span className="preview-form-icon-text">
                <img
                  className="preview-form-title-icon"
                  src="https://gw.alicdn.com/tfs/TB1GuaQq3MPMeJjy1XdXXasrXXa-144-144.png"
                />
                <span className="preview-form-title-text">
                  {baseInfo.name}的入职登记表
                </span>
              </span>
              <span className="preview-form-title-status">
                {profile.submitEntryTable ? (
                  <div className="preview-form-title-status-success">
                    已提交 <br />
                    {profile.modifiedEntryTableTime}
                  </div>
                ) : (
                  <span className="preview-form-title-status-failure">未提交</span>
                )}
              </span>
            </div>
          )}

          {customList
            .map(item => ({
              list: getComponents(item.customFieldVOList || []),
              title: item.title
            }))
            .map(({ list, title }, idx) => (
              <Card key={idx} title={title}>
                <ProduceComponent list={list || []} />
              </Card>
            ))}
        </div>

        {hasPermission && profile.employeeStatus !== "4" && (
          <div className="scroll-btn scroll-btn-preview">
            <Button
              className="preview-button"
              type="primary"
              onClick={this.showActionSheet.bind(this, isEdit)}
            >
              操作
            </Button>
          </div>
        )}
      </div>
    );
  }
}
